-
Notifications
You must be signed in to change notification settings - Fork 0
/
Detect Nagetive Weight Cycle Using Bellmen Ford Algorithm - Edge List.cpp
74 lines (65 loc) · 1.74 KB
/
Detect Nagetive Weight Cycle Using Bellmen Ford Algorithm - Edge List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <map>
#include <vector>
#include <climits>
#include <tuple>
using namespace std;
class Graph {
private:
vector <tuple<int, int, int>> edges;
public:
void addEdge(int u, int v, int w){
edges.push_back(make_tuple(u, v, w));
}
void print(){
cout << " U V W" << endl;
cout << "------------" << endl;
int u, v, w;
for(auto edge:edges){
cout << "{";
tie(u, v, w) = edge;
cout << u << " " << v << (w < 0 ? " " : " ") << w;
cout << "}" << endl;
}
}
void BellmanFord(int src, int n){
vector <int> distance(n, INT_MAX);
distance[src] = 0;
// Start Algorithm
int u, v, w;
for(int i = 0; i < n-1; i++){
for(auto edge:edges){
tie(u, v, w) = edge;
if(distance[u] != INT_MAX && (distance[u]+w) < distance[v]){
distance[v] = (distance[u]+w);
}
}
}
// Detect Cycle
for(int i = 0; i < n-1; i++){
for(auto edge:edges){
tie(u, v, w) = edge;
if(distance[u] != INT_MAX && (distance[u]+w) < distance[v]){
cout << "Graph contains nagetive weight cycle" << endl;
return;
}
}
}
// Print Distance
cout << endl << "Distance From " << src << " to N: ";
for(auto val:distance){
cout << val << " ";
}
cout << endl;
}
};
int main(){
Graph G;
G.addEdge(0, 1, 2);
G.addEdge(1, 2, -2);
G.addEdge(2, 0, -1);
cout << "Edge List: " << endl;
G.print();
int n = 3;
G.BellmanFord(0, n);
}